<template>
  <div class="settings-page">
    <!-- 头部区域 -->
    <div class="header">
      <el-row justify="space-between" align="middle">
        <el-col>
          <el-icon><ArrowLeft /></el-icon> 
        </el-col>
        <el-col>
          <h3>设置</h3>
        </el-col>
        <el-col></el-col>
      </el-row>
    </div>

    <!-- 头像上传区域 -->
    <el-card class="settings-list" shadow="never">
      <el-row class="setting-item" align="middle">
        <el-col :span="6">头像</el-col>
        <el-col :span="18" class="right-col">
          <el-upload
            class="avatar-uploader"
            :action="avatarUploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            method="post">
            <img v-if="user.pic_url" :src="user.pic_url" class="avatar" alt="User Avatar">
            <el-avatar v-else src="https://via.placeholder.com/50x50.png?text=头像"></el-avatar>
          </el-upload>

        </el-col>
      </el-row>

      <!-- 手机号输入框 -->
      <el-row class="setting-item" align="middle">
        <el-col :span="6">用户手机号</el-col>
        <el-col :span="18" class="right-col">
          <el-input v-model="user.mobile" placeholder="请输入手机号"></el-input>
        </el-col>
      </el-row>

      <!-- 用户名输入框 -->
      <el-row class="setting-item" align="middle">
        <el-col :span="6">用户名</el-col>
        <el-col :span="18" class="right-col">
          <el-input v-model="user.nikename" placeholder="请输入用户名"></el-input>
        </el-col>
      </el-row>

      <!-- 积分展示 -->
      <el-row class="setting-item" align="middle">
        <el-col :span="6">我的积分</el-col>
        <el-col :span="18" class="right-col">
          <span>{{ user.tscore }}</span>
        </el-col>
      </el-row>

      <!-- 保存按钮 -->
      <el-row class="setting-item" align="middle">
        <el-col :span="6">保存更改</el-col>
        <el-col :span="18" class="right-col">
          <el-button type="primary" @click="saveUserInfo">保存</el-button>
        </el-col>
      </el-row>

      <!-- 登出按钮 -->
      <el-row class="logout-section">
        <el-button type="primary" size="large" @click="logout">退出登录</el-button>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import axios from 'axios';

const router = useRouter();
const user = reactive({
  id: '',
  mobile: '',
  nikename: '',
  pic_url: '',
  tscore: 0
});

const userId = localStorage.getItem('userid');
const avatarUploadUrl = computed(() => `http://127.0.0.1:8000/user/update/${userId}/`);

onMounted(async () => {
  if (!userId) {
    console.error('User ID not found. Redirecting to login.');
    router.push('/login');
    return;
  }

  try {
    // 向后端请求获取用户信息
    const response = await axios.get('http://127.0.0.1:8000/user/info/');
    if (response.data.code === 200) {
      const userData = response.data.data.find(item => item.id === parseInt(userId));
      if (userData) {
        // 更新用户信息
        user.id = userData.id;
        user.mobile = userData.mobile;
        user.nikename = userData.nikename;
        user.pic_url = `http://127.0.0.1:8000${userData.pic_url}`;
        user.tscore = userData.tscore;
      }
    } else {
      console.error('未能加载用户信息');
    }
  } catch (err) {
    console.error('未能获取用户信息:', err);
  }
});

const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    user.pic_url = response.pic_url; // 使用后端返回的完整图片路径更新用户头像
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error('上传失败，请重试');
  }
};

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('上传的文件必须是图片格式');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传的图片大小不能超过 2MB');
    return false;
  }
  return true;
};

const saveUserInfo = async () => {
  try {
    const formData = new FormData();
    formData.append('mobile', user.mobile);
    formData.append('nikename', user.nikename);

    const response = await axios.post(avatarUploadUrl.value, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });

    if (response.data.code === 200) {
      Object.assign(user, response.data.data);
      ElMessage.success('用户信息更新成功');
    } else {
      ElMessage.error('用户信息更新失败');
    }
  } catch (err) {
    ElMessage.error('请求出错，请稍后重试');
  }
};

const logout = () => {
  localStorage.removeItem('userid');
  router.push('/login');
};
</script>

<style scoped>
.settings-page {
  font-family: Arial, sans-serif;
  background-color: #f5f5f5;
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.header {
  padding: 10px 0;
  background-color: white;
  text-align: center;
  border-bottom: 1px solid #ebebeb;
}

.setting-item {
  padding: 15px 0;
  border-bottom: 1px solid #ebebeb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-col {
  display: flex;
  align-items: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  cursor: pointer;
}

.logout-section {
  margin-top: 30px;
  text-align: center;
}

.logout-button {
  background-color: #67c23a;
  color: white;
  width: 100%;
  padding: 10px 0;
  border-radius: 5px;
  font-size: 16px;
}

.el-input {
  width: 100%;
  margin-top: 5px;
}
</style>
